package com.ling.tools.login.netty;

import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author LiangLing
 * @Description TODO
 * @Date 2019/12/17
 **/
public class Connections {
    private ConcurrentHashMap<String , ChannelHandlerContext>  connectionsMap = null;

    static private Connections socketConnections = null;

    public ConcurrentHashMap<String, ChannelHandlerContext> getConnectionsMap() {
        return connectionsMap;
    }

    private Connections() {
        connectionsMap = new ConcurrentHashMap<>();
    }

    static public Connections getInstance() {

        if (socketConnections == null) {
            socketConnections = new Connections();
        }
        return socketConnections;
    }

    /**
     * Save the connection.
     * When connection is connected , call this method to save connection.
     */
    public void saveConnection(String key , ChannelHandlerContext ctx) {

        connectionsMap.put(key, ctx);
    }

    /**
     * Delete the connection.
     * When connection is timeout , dead or has exceptions , call this method to delete connection.
     */
    public void deleteConnection(String key) {

        connectionsMap.remove(key);
    }

    /**
     * Get the ChannelHandlerContext.
     * Get the ChannelHandlerContext that you want.
     */
    public ChannelHandlerContext getConnection(String key) {
        return connectionsMap.get(key);
    }

}
